package com.sxm.yiwei.activitis;


import android.content.ContentResolver;
import android.content.Context;

import android.content.Intent;
import android.content.SharedPreferences;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;


import android.support.v7.app.AlertDialog;

import android.text.TextUtils;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.BaseIntents;
import com.sxm.yiwei.tools.CropPictures;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MineMember extends BaseActivity implements View.OnClickListener{
    public static final String TAG = "member";
    private Button updata;
    private ImageView memberback;
    private ImageView shenfenz;
    private ImageView shenfenf;
    private ImageView shenfenr;

    /*用来标识请求照相功能的activity*/
    private static final int CAMERA_WITH_DATA = 3023;
    /*用来标识请求gallery的activity*/
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    private List<Object> imgId = new ArrayList<>();

    private Bitmap photo;
    // 按钮标志
    private int currentIndex;

    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;

    private EditText linkmanname;
    private EditText linkmanphone;
    private EditText name;
    private EditText sfno;
    private String linmanName;
    private String linkmanPhone;
    private String nameT;
    private String sfNo;
    private Button women;
    private Button man;
    private static final int PHOTO_TEXT = 3022;
    private String path1;
    private List<String>imglist = new ArrayList();
    private AlertDialog dialog;
    private BaseIntents baseIntents;
    private ImageView backmain;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_member);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("userId", "1");
        token = sharedPreferences.getString("token", "2");
        initMineMemberView();
        baseIntents = new BaseIntents();
    }
        // 获取输入信息
    private void getInPutData() {
        linmanName = String.valueOf(linkmanname.getText());
        linkmanPhone = String.valueOf(linkmanphone.getText());
        nameT = String.valueOf(name.getText());
        sfNo = String.valueOf(sfno.getText());

    }


    private void initMineMemberView() {
        backmain = (ImageView) findViewById(R.id.minemenber_backmain);
        updata = (Button) findViewById(R.id.mine_member_updatebt);
        memberback = (ImageView) findViewById(R.id.mine_member_back);
        linkmanname = (EditText) findViewById(R.id.number_linkmanname);
        linkmanphone = (EditText) findViewById(R.id.number_linkmanphone);
        name = (EditText) findViewById(R.id.number_name);
        sfno = (EditText) findViewById(R.id.number_sfno);
        // 身份证设置页面
        shenfenz = (ImageView) findViewById(R.id.sfzz);
        shenfenf = (ImageView) findViewById(R.id.sfzf);
        shenfenr = (ImageView) findViewById(R.id.sfzr);
        imgId.add(R.id.sfzz);
        imgId.add(R.id.sfzf);
        imgId.add(R.id.sfzr);
        shenfenz.setOnClickListener(this);
        backmain.setOnClickListener(this);
        shenfenf.setOnClickListener(this);
        shenfenr.setOnClickListener(this);
        women = (Button) findViewById(R.id.number_sex1);
        man = (Button) findViewById(R.id.number_sex2);
        memberback.setOnClickListener(this);
        updata.setOnClickListener(this);
        women.setOnClickListener(this);
        man.setOnClickListener(this);
    }
    private String sex;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.minemenber_backmain:
                startActivity(new Intent(MineMember.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.mine_member_back:
                finish();
                break;
            case R.id.number_sex1:
                sex="1";
                women.setSelected(true);
                man.setSelected(false);
                break;
            case R.id.number_sex2:
                sex="2";
                women.setSelected(false);
                man.setSelected(true);
                break;
            case R.id.sfzz://正面身份证
                doPickPhotoAction();
                currentIndex = 0;
                break;
            case R.id.sfzf:// 反面身份证
                doPickPhotoAction();
                currentIndex = 1;
                break;
            case R.id.sfzr://手持身份证照片
                doPickPhotoAction();
                currentIndex = 2;
                break;
            case R.id.mine_member_updatebt:
                if (TextUtils.isEmpty(nameT)){
                    Toast.makeText(this, "请输入您的姓名", Toast.LENGTH_SHORT).show();
                }else if (TextUtils.isEmpty(sfNo)){
                    Toast.makeText(this, "请输入您的身份证号码", Toast.LENGTH_SHORT).show();
                }else if (TextUtils.isEmpty(linmanName)){
                    Toast.makeText(this, "请输入您的身份证号码", Toast.LENGTH_SHORT).show();
                }else if (TextUtils.isEmpty(linkmanPhone)){
                    Toast.makeText(this, "请输入您的身份证号码", Toast.LENGTH_SHORT).show();
                }else if (imglist.size()>3){
                    Toast.makeText(this, "请输入您的身份证号码", Toast.LENGTH_SHORT).show();
                }else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MineMember.this, R.style.NoBackGroundDialog);
                    View view = LayoutInflater.from(this).inflate(R.layout.progress_dialog, null);
                    builder.setView(view);
                    dialog = builder.create();
                    dialog.show();
                    upSfData();
                }

                break;
        }
    }
        // 提交身份资料
    private void upSfData() {
        getInPutData();

        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/userInfo/submitIdentityAudit");
        params.addHeader("Content-Type","multipart/form-data");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        params.addBodyParameter("name",nameT);
        params.addBodyParameter("identity",sfNo);
        params.addBodyParameter("sex","2");
        params.addBodyParameter("emerName",linmanName);
        params.addBodyParameter("emerPhone",linkmanPhone);
        for (int i1 = 0; i1 < imglist.size(); i1++) {
            params.addBodyParameter("identityAuth",new File(imglist.get(i1)));
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                dialog.dismiss();


                Toast.makeText(MineMember.this, "您的信息上传成功，请耐心等待审核", Toast.LENGTH_SHORT).show();
            finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                dialog.dismiss();
                ErrType.errType(MineMember.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

    private void doPickPhotoAction() {
        final Context context = this;
        AlertDialog.Builder b1 = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.picture_dialog, null);
        b1.setView(view);

        TextView camere = (TextView) view.findViewById(R.id.picdia_camere);
        TextView pic = (TextView) view.findViewById(R.id.picdia_pic);
        TextView cancel1 = (TextView) view.findViewById(R.id.picdia_cancel);

        final AlertDialog dialog1 = b1.create();
        Window window = dialog1.getWindow();
        camere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String status= Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
                    // index=0;
                    baseIntents.doTakePhoto();// 用户点击了从照相机获取
                    dialog1.dismiss();
                }
                else{
                    Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseIntents.doPickPhotoFromGallery();// 从相册中去获取
                dialog1.dismiss();
            }
        });
        cancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });
        dialog1.show();
        window.setGravity(Gravity.BOTTOM);
    }


    // 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的

                photo = data.getParcelableExtra("data");
                String s = CropPictures.saveBitmapFile(photo, baseIntents.getPhotoFileName());
                imglist.add(s);
                if (currentIndex==0){
                    shenfenz.setImageBitmap(photo);
                }else if (currentIndex==1){
                    shenfenf.setImageBitmap(photo);
                }else if (currentIndex==2){
                    shenfenr.setImageBitmap(photo);
                }
                break;
            }
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                baseIntents.doCropPhoto(baseIntents.mCurrentPhotoFile);

                break;
            }
            case PHOTO_TEXT:
                Uri data1 = data.getData();
                if (!TextUtils.isEmpty(data1.getAuthority())){
                    ContentResolver resolver = getContentResolver();
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, data1);
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(data1, proj, null, null, null);
                        if (cursor==null){
                            Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }else {
                            cursor.moveToFirst();
                            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            //图片路径
                            path1 = cursor.getString(column_index);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    path1 = data1.getPath();
                }
                File file = new File(path1);
                baseIntents.doCropPhoto(file);
                break;
        }


    }


}
